import type { RouteRecordRaw } from 'vue-router'

function dynamicImport(componentPath: string): () => Promise<any> {
  const normalizedPath = componentPath.startsWith('/')
    ? componentPath.slice(1)
    : componentPath
  return () => import(`@/views/${normalizedPath}.vue`)
}

export function transformAsyncRoutes(routes: any[]): RouteRecordRaw[] {
  return routes.map((route) => {
    const { path, name, component, redirect, meta, children } = route

    const newRoute: any = {
      path,
      name,
      meta: meta || {},
    }

    if (redirect) newRoute.redirect = redirect

    // 动态导入组件
    if (component) {
      if (component === 'Layout' || component === '/layout/index') {
        newRoute.component = () => import('@/layout/index.vue')
      } else {
        newRoute.component = dynamicImport(component)
      }
    } else if (children && children.length) {
      newRoute.component = () => import('@/layout/index.vue')
    }

    if (children && Array.isArray(children)) {
      newRoute.children = transformAsyncRoutes(children)
    }

    return newRoute as RouteRecordRaw
  })
}
